# The notes get from STHDA
library(ggplot2)
library(dplyr)
library(hexbin)

data(mtcars)
df <- mtcars[, c("mpg", "cyl", "wt")]
df$cyl <- as.factor(df$cyl)

# Scatter (point plot)
qplot(x = mpg, y = wt, data = df, geom = "point")
ggplot(data = df, aes(x = mpg, y = wt)) +
  geom_point()

qplot(x = mpg, y = wt, data = df, geom = c("point", "smooth"))

qplot(x = mpg, y = wt, data = df, color = cyl, shape = cyl)

ggplot(data = df, aes(x = mpg, y = wt)) +
  geom_point(color = "blue", size = 2, shape = 23)

# Boxplot, Violin plot & Dot plot
set.seed(1234)
wdata <- data.frame(
  sex = factor(rep(c("F", "M"), each = 200)),
  weight = c(rnorm(200, 55), rnorm(200, 58)))

qplot(sex, weight, data = wdata, geom = "boxplot", fill = sex)

qplot(sex, weight, data = wdata, geom = "violin")

qplot(sex, weight, data = wdata, geom = "dotplot",
      stackdir = "center", binaxis = "y", dotsize = 0.5, color = sex)

# Histogram, density plot
qplot(weight, data = wdata, geom = "histogram", fill = sex)

qplot(weight, data = wdata, geom = "density", color = sex, linetype = sex)

ggplot(wdata, aes(x = weight)) +
  geom_density() # stat_density() has the same effect


#1. One variable [continuous] ----
mu <- wdata %>% group_by(sex) %>% summarise(grp.mean = mean(weight)) 

a <- ggplot(wdata, aes(x = weight))

##1.1 Area plot
a + geom_area(stat = "bin")

a + geom_area(aes(fill = sex), stat = "bin", alpha = 0.6) + theme_classic()

a + geom_area(aes(y = ..density..), stat = "bin")

##1.2 Density
a + geom_density()

a + geom_density(aes(color = sex))

a + geom_density(aes(fill = sex), alpha = 0.4)

a + geom_density(aes(color = sex)) +
  geom_vline(data = mu, 
             aes(xintercept = grp.mean, color = sex), linetype = "dashed") +
  scale_color_manual(values = c("red", "blue"))

##1.3 Dot plot
a + geom_dotplot(aes(fill = sex)) +
  scale_fill_manual(values = c("#999999", "#E69F00"))

##1.4 Frequent plot
a + geom_freqpoly(aes(color = sex, linetype = sex)) + theme_minimal()

a + geom_freqpoly(aes(y = ..density..)) + theme_minimal()

##1.5 Histogram
a + geom_histogram(aes(color = sex), fill = "white", position = "dodge") +
  theme_minimal()

##1.6 Cumulative density plot
a + stat_ecdf()

##1.7 QQ plot
ggplot(mtcars, aes(sample = mpg)) + stat_qq()


#2. One variable [discrete] ----
## Bar plot
ggplot(mpg, aes(x = fl)) + 
  geom_bar(fill = "steelblue", color = "black") + theme_classic()


#3. Two variables [continous, continous] ----
b <- ggplot(mtcars, aes(x = wt, y = mpg))

##3.1 Scatter plot
b + geom_point(aes(color = factor(cyl), shape = factor(cyl)))

b + geom_point(aes(color = factor(cyl), shape = factor(cyl))) +
  scale_color_manual(values = c("#999999", "#E69F00", "#56B4E9")) +
  theme_classic()

##3.2 Regression line
b + geom_point() + geom_smooth(method = "lm", se = FALSE)

b + geom_point() + geom_smooth(method = "loess")

b + geom_point(aes(color = factor(cyl), shape = factor(cyl))) +
  geom_smooth(aes(color = factor(cyl)), method = "lm", se = F, fullrange = T)

##3.3 Quantile line
ggplot(mpg, aes(cty, hwy)) + geom_point() + 
  geom_quantile() + theme_minimal()

##3.4 Marginal rug to scatter plots
ggplot(faithful, aes(eruptions, waiting)) + geom_point() + geom_rug()

p <- ggplot(mpg, aes(displ, hwy))
p + geom_point()
p + geom_jitter(width = 0.5, height = 0.5) # geom_point(position = "jitter")

##3.5 Text annonation
b + geom_text(aes(label = rownames(mtcars)))


#4. Two variables [continous bivariate distribution] ----
c <- ggplot(diamonds, aes(carat, price))

##4.1 Heatmap of 2d bin counts
c + geom_bin2d(bins = 50)

##4.2 Hexagon bining
c + geom_hex(bins = 10)

##4.3 Contours from 2d density estimate
sp <- ggplot(faithful, aes(eruptions, waiting))
sp + geom_point() + geom_density_2d()


#5. Two variables [continous fucntions] ----
## Connect observations by line
d <- ggplot(economics, aes(date, unemploy))

d + geom_area() # area plot

d + geom_line() # line plot connecting observations, ordered by x

## Connecting observations by stairs
set.seed(1111)
ss <- economics[sample(1:nrow(economics), 20), ]
ggplot(ss, aes(date, unemploy)) + geom_step()


#6. Two variables [discrete X, continous Y] ----
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
e <- ggplot(ToothGrowth, aes(dose, len))

##6.1 Box plot
e + geom_boxplot()

e + geom_boxplot(notch = TRUE) # Notched box plot

e + geom_boxplot(aes(color = dose))

e + geom_boxplot(aes(fill = dose))

ggplot(ToothGrowth, aes(dose, len)) + geom_boxplot(aes(fill = supp))

##6.2 Violin plot
e + geom_violin(trim = F)

e + geom_violin(trim = FALSE) +
  stat_summary(fun.data = mean_sdl, fun.args = list(mult = 1),
               geom = "pointrange", color = "red") # Violin with mean points

e + geom_violin(trim = FALSE) + geom_boxplot(width = 0.2) # Violin + boxplot

e + geom_violin(aes(color = dose), trim = F)

##6.3 Dot plot
e + geom_dotplot(binaxis = "y", stackdir = "center")

e + geom_dotplot(binaxis = "y", stackdir = "center") +
  stat_summary(fun.data = mean_sdl, color = "red",  # Add mean point
               geom = "pointrange", fun.args = list(mult = 1))

e + geom_boxplot() + # with box plot
  geom_point(binaxis = "y", stackdir = "center")

e + geom_violin(trim = FALSE) + # with violin
  geom_dotplot(binaxis = "y", stackdir = "center")

e + geom_dotplot(aes(color = dose, fill = dose),
                 binaxis = "y", stackdir = "center")

##6.4 Strip charts
e + geom_jitter(position = position_jitter(0.2))

e + geom_jitter(position = position_jitter(0.2)) + # with mean point (+/-SD)
  stat_summary(fun.data = mean_sdl, fun.args = list(mult = 1),
               geom = "pointrange", color = "red")

e + geom_jitter(position = position_jitter(0.2)) + # with box plot
  geom_dotplot(binaxis = "y", stackdir = "center")

e + geom_violin(trim = FALSE) + # with violin plot
  geom_jitter(position = position_jitter(0.2))

e + geom_jitter(aes(color = dose, shape = dose),
                position = position_jitter(0.2))

##6.5 Line plot
df <- data.frame(supp = rep(c("VC", "OJ"), each = 3),
                 dose = rep(c("D0.5", "D1", "D2"), 2),
                 len = c(6.8, 15, 33, 4.2, 10, 29.5))

ggplot(df, aes(dose, len, group = supp)) +
  geom_line(aes(linetype = supp, color = supp)) + 
  geom_point(aes(shape = supp, color = supp))

##6.6 Bar plot
df <- data.frame(dose = c("D0.5", "D1", "D2"), len = c(4.2, 10, 29.5))

df2 <- data.frame(
  supp = rep(c("VC", "OJ"), each = 3),
  dose = rep(c("D0.5", "D1", "D2"), 2),
  len = c(6.8, 15, 33, 4.2, 10, 29.5))

f <- ggplot(df, aes(dose, len))
f + geom_bar(stat = "identity")
f + geom_col()

f + geom_bar(stat = "identity", fill = "steelblue") +
  geom_text(aes(label = len), vjust = -0.3, size = 3.5) + # Add labels
  theme_minimal()

f + geom_bar(aes(color = dose), stat = "identity", fill = "white")

f + geom_bar(aes(fill = dose), stat = "identity")

g <- ggplot(df,aes(dose, len, fill = supp))
g + geom_bar(stat = "identity") # position = stack (default)

g + geom_bar(stat = "identity", position = position_dodge())

# Key function: geom_bar()
# Alternative function: stat_identity()
g + stat_identity(geom = "bar")
g + stat_identity(geom = "bar", position = "dodge")


#7. Two variables [discrete X, discrete Y] ----
## Key function: geom_jitter()
ggplot(diamonds, aes(cut, color)) +
  geom_jitter(aes(color = cut), size = 0.5)


#8. Visualizing error (two variables) ----
dtg <- ToothGrowth
dtg$dose <- as.factor(dtg$dose)

##8.1 Cross bar (hollow bar with middle indicated by horizontal line)
dtg2 <- ToothGrowth %>% group_by(dose) %>% 
  summarise(len.m = mean(len), len.sd = sd(len))
dtg2$dose <- as.factor(dtg2$dose)

f <- ggplot(dtg2, aes(dose, len.m, 
                      ymin = len.m - len.sd, ymax = len.m + len.sd))

# Change color manually
f + geom_crossbar(aes(color = dose)) +
  scale_color_manual(values = c("#999999", "#E69F00", "#56B4E9")) +
  theme_classic()

f + geom_crossbar(aes(fill = dose)) +
  scale_fill_manual(values = c("#999999", "#E69F00", "#56B4E9")) +
  theme_classic()

f <- ggplot(dtg, aes(dose, len, color = supp))
f + stat_summary(fun.data = mean_sdl, fun.args = list(mult = 1),
                 geom = "crossbar", width = 0.6, position = position_dodge(0.8))

##8.2 Error bars
f <- ggplot(dtg2, aes(dose, len.m, 
                      ymin = len.m - len.sd, ymax = len.m + len.sd))
f + geom_errorbar(aes(color = dose), width = 0.2)

f + geom_line(aes(group = 1)) + geom_errorbar(width = 0.15) # with line

f + geom_bar(aes(color = dose), stat = "identity", fill = "white") + # with bar
  geom_errorbar(aes(color = dose), width = 0.1)

##8.3 Horizontal error bar
f <- ggplot(dtg2, aes(len.m, dose, 
                      xmin = len.m - len.sd, xmax = len.m + len.sd))
f + geom_errorbarh(aes(color = dose))

##8.4 Linerange & pointrange
f <- ggplot(dtg2, aes(dose, len.m, 
                      ymin = len.m - len.sd, ymax = len.m + len.sd))
f + geom_linerange()  # Line range
f + geom_pointrange() # Point range

##8.5 Dot and errorbar
g <- ggplot(dtg, aes(dose, len)) +
  geom_dotplot(binaxis = "y", stackdir = "center")

g + stat_summary(fun.data = mean_sdl, fun.args = list(mult = 1),
                 geom = "crossbar", color = "red", width = 0.1)

g + stat_summary(fun.data = mean_sdl, fun.args = list(mult = 1),
                 geom = "errorbar", color = "red", width = 0.1)

g + stat_summary(fun.data = mean_sdl, fun.args = list(mult = 1),
                 geom = "pointrange", color = "red")


#9. Map (two variables) ----
library(maps)
crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)

library(reshape2)
crimesm <- melt(crimes, id = 1)
map_data <- map_data("state")
ggplot(crimes, aes(map_id = state)) +
  geom_map(aes(fill = Murder), map = map_data) +
  expand_limits(x = map_data$long, y = map_data$lat)


#10. Three variables ----
# Key functions: geom_tile(), geom_raster()
df <- mtcars[, c(1, 3, 4, 5, 6, 7)]

# geom_tile(): Tile plane with rectangles (similar to levelplot and image)
# geom_raster(): High-performance rectangular tiling. This is a special case of 
#   geom_tile where all tiles are the same size.

cormat <- round(cor(df), 2) # computer the correlation
cormat_melt <- melt(cormat)

g <- ggplot(cormat_melt, aes(x = Var1, y = Var2))

get_lower_tri <- function(cormat) {
  cormat[upper.tri(cormat)] <- NA
  return(cormat)
}

get_upper_tri <- function(cormat) {
  cormat[lower.tri(cormat)] <- NA
  return(cormat)
}

upper.tri <- get_upper_tri(cormat = cormat) # get the upper triangle
upper.tri.melt <- melt(upper.tri, na.rm = TRUE)

# Red means positive correlation, blue means negative correlation.
ggplot(upper.tri.melt, aes(Var1, Var2, fill = value)) +
  geom_tile(color = "white") +
  scale_fill_gradient2(low = "blue", high = "red", mid = "white", 
                       midpoint = 0, limit = c(-1, 1), space = "Lab",
                       name = "Person\nCorrelation") +
  theme_minimal() +
  theme(axis.title.x = element_text(angle = 45, vjust = 1, 
                                    size = 12, hjust = 1)) +
  coord_fixed()

# Reorder the correlation matrix by hierarchical clustering
reorder_cormat <- function(cormat) {
  dd <- as.dist((1 - cormat) / 2)
  hc <- hclust(dd)
  cormat <- cormat[hc$order, hc$order]
}

cormat <- reorder_cormat(cormat)
lower.tri <- get_lower_tri(cormat)
lower.tri.melt <- melt(lower.tri, na.rm = T) # melt the correlation matrix

ggheatmap <- ggplot(lower.tri.melt, aes(Var1, Var2, fill = value)) +
  geom_tile(color = "white") + # Create the heatmap
  scale_fill_gradient2(low = "blue", high = "red", mid = "white",
                       midpoint = 0, limit = c(-1, 1), # change gradient
                       space = "Lab", name = "Person\nCorrelation") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, vjust = 1, 
                                   size = 12, hjust = 1)) +
  coord_fixed()

print(ggheatmap)


#10. Polygon, path, ribbon, curve, rect, segment ----

##10.1 Polygon (Map)
map_data("world") %>% 
  filter(region == c("China", "Taiwan")) %>% 
  ggplot(aes(long, lat, group = group)) +
  geom_polygon(fill = "red", color = "black")

##10.2 Path
h <- ggplot(economics, aes(date, unemploy))
h + geom_path()

##10.3 Ribbon
h + geom_ribbon(aes(ymin = unemploy - 800, ymax = unemploy + 800), 
                fill = "grey70") +
  geom_line(aes(y = unemploy))

##10.4 Rect
h + geom_path() +
  geom_rect(aes(xmin = as.Date("1980-01-01"), ymin = -Inf, 
                xmax = as.Date("1985-01-01"), ymax = Inf), fill = "steelblue")

##10.5 Segment (single line), (x1, y1) -> (x2, y2)
i <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
i + geom_segment(aes(x = 2, y = 15, xend = 3, yend = 15))

##10.6 Arrow
i + geom_segment(aes(x = 5, y = 30, xend = 3.5, yend = 25), 
                 arrow = arrow(length = unit(0.5, "cm")))

##10.7 Curve
i + geom_curve(aes(x = 2, y = 15, xend = 3, yend = 15), color = "red")


#11. Figure parameters ----
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
p <- ggplot(ToothGrowth, aes(dose, len)) + geom_boxplot()

##11.1 Title
# p + ggtitle("New main title") Adds a main title above the plot

# Change the title and axis labels
p <- p + labs(title = "Plot of length\nby dose", 
              x = "Dose (mg)", y = "Teeth length")
print(p)

##11.2 Label
# p + xlab("New X axis label"), change the X axia label
# p + ylab("New Y axis label"), change the Y axia label
# p + labs(title = "main title", x = "X axis label", y = "Y axis label")
#  Changes main title and axis labels

# Change the appearance of labels
p + theme(plot.title = element_text(color = "red", 
                                    size = 14, face = "bold.italic"),
          axis.title.x = element_text(color = "blue", 
                                      size = 14, face = "bold"),
          axis.title.y = element_text(color = "#993333", 
                                      size = 14, face = "bold"))

# Hiden label
p + theme(
  plot.title = element_blank(),
  axis.title.x = element_blank(), axis.line.y = element_blank()
)

##11.3 Legend
p <- ggplot(ToothGrowth, aes(dose, len, fill = dose)) +
  geom_boxplot() +
  labs(fill = "Dose (mg)") # Change the title of legend
print(p)

# Position of legend (top, left, right, bottom, none)
p + theme(legend.position = "top")

p + theme(legend.position = "none") # Del the legend

p + theme(legend.title = element_text(color = "blue"), # Modify the background
          legend.text = element_text(color = "red"))

# Modifing legend manually
p + scale_x_discrete(limits = c("2", "0.5", "1")) # Change the order of labels

# Content of legend
p + scale_fill_discrete(name = "Dose", label = c("A", "B", "C"))

##11.3 Change color
mtcars$cyl <- as.factor(mtcars$cyl)

bp <- ggplot(ToothGrowth, aes(dose, len))
sp <- ggplot(mtcars, aes(wt, mpg))

# Change fill and outline colors
bp + geom_boxplot(fill = "steelblue", color = "red")
sp + geom_point(color = "darkblue")

# Change color by groups
bp <- bp + geom_boxplot(aes(fill = dose))
print(bp)

sp <- sp + geom_point(aes(color = cyl))
print(sp)

# Change colors manually
bp + scale_fill_manual(values = c("#999999", "#E69F00", "#56B4E9"))
sp + scale_color_manual(values = c("#999999", "#E69F00", "#56B4E9"))

# RColorBrewer palette
bp + scale_fill_brewer(palette = "Dark2")
sp + scale_color_brewer(palette = "Dark2")

bp + scale_fill_grey() + theme_classic()
sp + scale_color_grey() + theme_classic()

# Gradient or continous colors
sp2 <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point(aes(color = qsec))

sp2 + scale_color_gradient(low = "blue", high = "red") # Sequential color scheme

mid <- mean(mtcars$qsec)
sp2 + scale_color_gradient2(midpoint = mid, low = "blue", mid = "white",
                            high = "red", space = "Lab")

# Point's color, size and shape
ggplot(mtcars, aes(wt, mpg)) +
  geom_point(shape = 18, color = "steelblue", size = 4)

ggplot(mtcars, aes(wt, mpg)) +
  geom_point(aes(shape = cyl, color = cyl))

# scale_shape_manual()
# scale_color_manual()
# scale_size_manual()
ggplot(mtcars, aes(wt, mpg, group = cyl)) +
  geom_point(aes(shape = cyl, color = cyl), size = 2) +
  scale_shape_manual(values = c(3, 16, 17)) +
  scale_color_manual(values = c('#999999','#E69F00', '#56B4E9')) +
  theme(legend.position = "top")


##11.4 Annotation
# geom_text(), Textual annotations
# geom_label()
# annotate(), Textual annotations
# annotation_custom(), Static annotations that are the same in every panel.
set.seed(1234)
df <- mtcars[sample(1:nrow(mtcars), 10), ]
df$cyl <- as.factor(df$cyl)

# Scatter plot and annotation
sp <- ggplot(df, aes(wt, mpg)) + geom_point()
sp + geom_text(aes(label = rownames(df), color = cyl), size = 3, vjust = -1)

# Add text at a particular coordinate
sp + geom_text(x = 3, y = 30, label = "Scatter plot", color = "red")

# Add label
sp + geom_label(aes(label = rownames(df)))

library(grid)
grob <- grobTree(textGrob("Scatter plot", x = 0.1, y = 0.93, hjust = 0, 
                          gp = gpar(col = "red", fontsize = 13, 
                                    fontface = "italic")))
sp + annotation_custom(grob)

# Annotation of facet
sp + annotation_custom(grob) + facet_wrap(~ cyl, scales = "free")

##11.5 Line types
# "blank", "solid", "dashed", "dotted", "dotdash"
# 0 -> 7
df2 <- data.frame(sex = rep(c("F", "M"), each = 3),
                  time = c("Breakfast", "Lunch", "Dinner"),
                           bill = c(10, 30, 15, 13, 40, 17))

# Line with multiple groups
ggplot(df2, aes(time, bill, group = sex)) +
  geom_line(aes(linetype = sex, color = sex)) +
  geom_point(aes(color = sex)) +
  theme(legend.position = "top")

# scale_linetype_manual()
# scale_color_manual()
# scale_size_manual()
ggplot(df2, aes(time, bill, group = sex)) +
  geom_line(aes(linetype = sex, color = sex, size = sex)) +
  geom_point() +
  scale_linetype_manual(values = c("twodash", "dotted")) +
  scale_color_manual(values = c('#999999','#E69F00')) +
  scale_size_manual(values = c(1, 1.5)) +
  theme(legend.position = "top")


#12. Theme and background ----
library(ggthemes)
ToothGrowth$dose <- as.factor(ToothGrowth$dose)

##12.1 Theme
p <- ggplot(ToothGrowth, aes(dose, len)) + geom_boxplot()

# Themes from ggplot2 package
p + theme_gray(base_size = 14) # gray background color and white grid lines
p + theme_bw() # white background and gray grid lines
p + theme_linedraw() # black lines around the plot
p + theme_light() # light gray lines and axis (more attention towards the data)
p + theme_minimal() # no background annotations
p + theme_classic() # theme with axis lines and no grid lines

# Themes from ggthemes package
p + theme_economist()

##12.2 Axis [max, min]
p <- ggplot(cars, aes(speed, dist)) + geom_point()

### 1. Without clipping (preferred)
p + coord_cartesian(xlim = c(5, 20), ylim = c(0, 50))

### 2. With clipping
p + xlim(5, 20) + ylim(0, 50)
p + scale_x_continuous(limits = c(5, 20)) + scale_y_continuous(limits = c(0,50))

### 3. Expand the limit with data
p + expand_limits(x = 0, y = 0) # intercept is 0
p + expand_limits(x = c(5, 50), y = c(0, 150))

##12.2 Modify axis
p + scale_x_log10() + scale_y_log10()
p + scale_x_sqrt() + scale_y_sqrt()
p + scale_x_reverse() + scale_y_reverse()
p + coord_trans(x = "log10", y = "log10")
p + scale_x_continuous(trans = "log2") + scale_y_continuous(trans = "log2")

# Change the label of ticks
library(scales)
p + scale_y_continuous(trans = log2_trans(),
                       breaks = trans_breaks("log2", function(x) 2 ^ x),
                       labels = trans_format("log2", math_format(2^.x)))

##12.3 Ticks
# element_text(face, color, size, angle)
# element_blank()

p <- ggplot(ToothGrowth, aes(dose, len)) + geom_boxplot()
p + theme(axis.text.x = element_text(face = "bold", color = "#993333", 
                                     size = 14, angle = 45),
          axis.text.y = element_text(face = "bold", color = "blue", 
                                     size = 14, angle = 45))

# Remove ticks labels
p + theme(axis.text.x = element_blank(),
          axis.text.y = element_blank(),
          axis.ticks = element_blank())

###12.3.1 Discrete axis
# scale_x_discrete(name, breaks, labels, limits)
# scale_y_discrete(name, breaks, labels, limits)

# Modify the ticks title and reorder
p + scale_x_discrete(name = "Dose (mg)", limits = c("2", "1", "0.5"))

# Modify the ticks label
p + scale_x_discrete(breaks = c("0.5", "1", "2"), 
                     labels = c("Dose 0.5", "Dose 1", "Dose 2"))

# Show part of data
p + scale_x_discrete(limits = c("0.5", "2"))

###12.3.2 Continous axis
# scale_x_continuous(name, breaks, labels, limits)
# scale_y_continuous(name, breaks, labels, limits)

sp <- ggplot(cars, aes(speed, dist)) + geom_point() +
  scale_x_continuous(name = "Speed of cars", limits = c(0, 30)) +
  scale_y_continuous(name = "Stopping distance", limits = c(0, 150))
print(sp)

# Change the interval of Y axis
sp + scale_y_continuous(breaks = seq(0, 150, 50))

# Show percents
sp + scale_y_continuous(labels = percent)


##12.4 Add straight lines
# geom_hline(yintercept = , linetype, color, size)
# geom_vline(yintercept = , linetype, color, size)
# geom_abline(intercept = , slope, linetype, color, size)
# geom_segment()
sp <- ggplot(mtcars, aes(wt, mpg)) + geom_point()

sp + geom_hline(yintercept = 20, linetype = "dashed", color = "red")
sp + geom_vline(xintercept = 3, color = "blue", size = 1.5)
sp + geom_abline(intercept = 37, slope = -5, color = "green")
sp + geom_segment(aes(x = 2, y = 15, xend = 3, yend = 15), color = "red")

##12.5 Rotation and reverse
# coord_flip()
# scale_x_reverse()
# scale_y_reverse()

set.seed(1234)
hp <- qplot(x = rnorm(200), geom = "histogram")
hp + coord_flip()
hp + scale_y_reverse()

##12.6 Position adjustement
p <- ggplot(mpg, aes(fl, fill = drv))

p + geom_bar(position = "dodge") # side by side
p + geom_bar(position = "stack") # stack top of one another
p + geom_bar(position = "fill")  # have equal height

ggplot(mpg, aes(cty, hwy)) + geom_point(position = "jitter") # avoid overplotting

# position_dodge(width, height)
# position_fill(width, height)
# position_stack(width, height)
# position_jitter(width, height)
p + geom_bar(position = position_dodge(width = 1))

##12.7 Axis
# p+coord_cartesian(xlim=NULL, ylim=NULL), Cartesian coordinate system (default)
# p+coord_fixed(ratio=1, clim=NULL, ylim=NULL)
#   Cartesian coordinates with fixed relationship between x and y. (ratio = 1)
# p+coord_flip(...), Flipped cartesian coordinates
# p+coord_polar(theta="x", start=0, direction=1), Polar coordinates
# p+coord_trans(x,y,limx,limy), Transformed cartesian coordinate system.
# coord_map(), map projections
p <- ggplot(mpg, aes(fl)) + geom_bar()
p + coord_cartesian(ylim = c(0, 200))
p + coord_fixed(ratio = 1 / 50)
p + coord_flip()
p + coord_polar(theta = "x", direction = 1)
p + coord_trans(y = "sqrt")

#13. Facet ----
# facet_grid()
# facet_wrap()
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
p <- ggplot(ToothGrowth, aes(dose, len, group = dose)) +
  geom_boxplot(aes(fill = dose))

# Facet ventically
p + facet_grid(supp ~ .)

# Facet horizontally
p + facet_grid(. ~ supp)

p + facet_grid(dose ~ supp) # X - dose, Y - supp
p + facet_grid(dose ~ supp, scales = "free") # Have different axis


# sessionInfo()